<template>
  <div class="wrapper">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            v-model="searchContent"
            @change="inputChange"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addUserFirstClick"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <template>
        <!-- 表格 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          stripe
        >
          <el-table-column
            type="index"
            label="#"
          > </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          > </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
          > </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话"
          > </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色"
          > </el-table-column>
          <el-table-column
            width="100px"
            prop="mg_state"
            label="状态"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="switchChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="200px"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="onEdit(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="onDelete(scope.row)"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配权限"
                placement="right"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="onCast(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userParams.pagenum"
        :page-sizes="[5, 10, 20, 25]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- Dialog -->
    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogAddUser"
      width="30%"
      :close-on-click-modal="false"
      @close="onCancle('add')"
    >
      <el-form
        :model="addUserParams"
        :rules="rules"
        label-width="100px"
        ref="addForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="addUserParams.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="addUserParams.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="Email"
          prop="email"
        >
          <el-input v-model="addUserParams.email"></el-input>
        </el-form-item>
        <el-form-item
          label="电话"
          prop="mobile"
        >
          <el-input v-model="addUserParams.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogAddUser = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onCommit"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="dialogEditUser"
      width="30%"
      :close-on-click-modal="false"
      @close="onCancle('edit')"
    >
      <el-form
        :model="editUserParams"
        :rules="rules"
        label-width="100px"
        ref="editForm"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="editUserParams.username"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="Email"
          prop="email"
        >
          <el-input v-model="editUserParams.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="editUserParams.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogEditUser = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onChangeCommit"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogCastRoles"
      width="30%"
      :close-on-click-modal="false"
      @close="onCancle('roles')"
    >
      <p>
        当前用户：<span>{{ roleUserParams.username }}</span>
      </p>
      <p class="center-role">
        当前的角色：<span>{{ roleUserParams.roleName }}</span>
      </p>
      <el-cascader
        :options="rolesList"
        @change="selectChange"
        :props="defaultData"
      ></el-cascader>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogCastRoles = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onCastRoles"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      userParams: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      addUserParams: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserParams: {
        email: '',
        mobile: '',
        id: 0
      },
      roleUserParams: {
        username: '',
        roleName: '',
        id: ''
      },
      tableData: [],
      total: 0,
      defaultQuery: '',
      searchContent: '',
      dialogAddUser: false,
      dialogEditUser: false,
      dialogCastRoles: false,
      rolesList: [],
      defaultData: {
        value: 'id',
        label: 'roleName',
        children: []
      },
      rid: 0,
      rules: {
        username: [
          { required: true, message: '请输入账户', trigger: 'blur' },
          { min: 3, max: 10, message: '账户在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '密码在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入Email', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserData();
  },
  methods: {
    async getUserData () {
      const { data: res } = await this.$http.get('users', {
        params: this.userParams
      })
      if (res.meta.status !== 200) return this.$message(res.meta.msg);
      this.tableData = res.data.users;
      this.total = res.data.total;
    },
    async switchChange (data) {
      const { data: res } = await this.$http.put(`/users/${data.id}/state/${data.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    async deleteUser (id) {
      const { data: res } = await this.$http.delete(`users/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserData();
    },
    async getRoleData () {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.setRoleData(res.data);
    },
    async setRemoteRole () {
      this.dialogCastRoles = false;
      const { data: res } = await this.$http.put(`users/${this.roleUserParams.id}/role`, { rid: this.rid });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserData();
    },
    setRoleData (data) {
      // var newArr = [];
      // data.forEach(item => {
      //   const obj = { value: item.id, label: item.roleName }
      //   newArr.push(obj);
      // });
      this.rolesList = data;
    },
    handleSizeChange (pageSize) {
      this.userParams.pagesize = pageSize;
      this.getUserData();
    },
    handleCurrentChange (page) {
      this.userParams.pagenum = page;
      this.getUserData();
    },
    inputChange () {
      this.userParams.query = this.searchContent;
      this.getUserData();
    },
    addUserFirstClick () {
      this.dialogAddUser = true;
      if (this.addUserParams.username === '') return;
      this.$refs.addForm.resetFields();
    },
    onCommit () {
      //添加用户
      this.$refs.addForm.validate(async (result) => {
        if (!result) return;
        this.dialogAddUser = false;
        //为了检索出刚刚添加的用户
        this.defaultQuery = this.addUserParams.username;
        const { data: res } = await this.$http.post('users', this.addUserParams);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg)
        this.userParams.pagesize = 1;
        this.userParams.query = this.defaultQuery;
        this.getUserData();
      });
    },
    onChangeCommit () {
      //修改用户
      this.$refs.editForm.validate(async (result) => {
        if (!result) return;
        this.dialogEditUser = false;
        const email = this.editUserParams.email;
        const mobile = this.editUserParams.mobile;
        const { data: res } = await this.$http.put(`users/${this.editUserParams.id}`, { email, mobile });
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg)
        this.getUserData();
      });
    },
    onCancle (str) {
      if (str === 'add') {
        this.$refs.addForm.validate((result) => {
          this.$refs.addForm.resetFields();
          this.dialogAddUser = false;
        });
      } else if (str === 'edit') {
        this.$refs.editForm.clearValidate()
      }
    },
    onDelete (data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(data.id)
      }).catch(() => {
      });
    },
    onEdit (data) {
      this.editUserParams.username = data.username;
      this.editUserParams.email = data.email;
      this.editUserParams.mobile = data.mobile;
      this.editUserParams.id = data.id;
      this.dialogEditUser = true
    },
    onCastRoles () {
      this.setRemoteRole();
    },
    onCast (data) {
      this.dialogCastRoles = true
      this.roleUserParams.username = data.username;
      this.roleUserParams.roleName = data.role_name;
      this.roleUserParams.id = data.id;
      this.getRoleData();
    },
    selectChange (arr) {
      this.rid = arr[0];
    }
  }
}
</script>
<style lang="scss" scoped>
.center-role {
  margin: 10px 0;
}
</style>
